package com.dgj.log.module.system;

import java.util.List;

import javax.servlet.http.HttpSession;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.lang.Strings;
import org.nutz.mvc.View;
import org.nutz.mvc.annotation.At;
import org.nutz.mvc.annotation.Attr;
import org.nutz.mvc.annotation.Ok;
import org.nutz.mvc.annotation.POST;
import org.nutz.mvc.annotation.Param;

import com.dgj.DefaultDESKey;
import com.dgj.biz.entitites.User;
import com.dgj.biz.entitites.auth.Role;
import com.dgj.biz.vo.VO;
import com.dgj.log.service.shiro.IShiroUserService;
import com.dgj.nutz.captcha.JPEGView;
import com.dgj.nutz.module.base.AbstractBaseModule;
import com.dgj.utils.encode.DES;
import com.dgj.utils.entries.Result;

/**
 * @author 肖山
 *
 *         create at 2015年4月22日 上午10:02:28
 */
@At("/system")
public class SystemModule extends AbstractBaseModule {

	@Inject
	private IShiroUserService shiroUserService;

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.dgj.nutz.module.base.AbstractBaseModule#_getNameSpace()
	 */
	@Override
	public String _getNameSpace() {
		return "system";
	}

	private boolean containRole(List<Role> roles, String roleName) {
		for (Role role : roles) {
			if (Strings.equals(roleName, role.getName())) {
				return true;
			}
		}
		return false;
	}

	@At("/login")
	@POST
	@Ok("json")
	public Result login(@Param("userName") String userName, @Param("password") String password, @Param("captcha") String captcha, boolean remember, HttpSession session) {
		if (Strings.equalsIgnoreCase(captcha, session.getAttribute(JPEGView.CAPTCHA).toString())) {
			Result result = shiroUserService.login(userName, password);
			if (result.isSuccess()) {
				_putSession(VO.SystemConst.USER_SESSION_KEY.getConfigValue(), result.getData().get("loginUser"));
				_putSession("community", result.getData().get("community"));
				if (remember) {
					_addCookie("dgj_titans", DES.encrypt(userName + ":" + password, DefaultDESKey.getKey()), 2 * 7 * 24 * 3600);
				}
			}
			return result;
		} else {
			return Result.fail("验证码输入错误");
		}
	}

	@At
	public Result logout(HttpSession session) {
		// session.invalidate();
		Subject subject = SecurityUtils.getSubject();
		if (subject.isAuthenticated()) {
			subject.logout(); // session 会销毁，在SessionListener监听session销毁，清理权限缓存
			if (log.isDebugEnabled()) {
				log.debug("用户退出登录");
			}
		}
		return Result.success();
	}

	@At
	public View main(@Attr("USER") User user) {
		List<Role> roles = shiroUserService.getAllRoles(user.getId());

		/**
		 * 如果用户有admin角色 那么进入admin后台
		 */
		if (containRole(roles, VO.InstalledRoles.PLAT_ADMIN)) {// 系统管理员
			return _renderRedirct("/main");
		}
		return null;
	}

}
